<template>
  <div class="app-container bg-grey">

    <div>
      <el-row :gutter="12" class="bg-fff bor-r-10 p20 mb20">
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </div>

    <el-row justify="center" :gutter="10" class="mb110">
        <el-checkbox-group v-model="ids">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-for="(item, i) in agentList" >
            <el-card shadow="hover" class="card-diy mb10">
              <el-checkbox :label="item.assistant_id" v-show="false"/>
                <div @click="toggleCheckbox(item)">
                  <div class="card-header">
                    <div class="card-title" :class="item.checked?'card-checked':''">{{ item.name }}</div>
                    <dict-tag class="right" :options="agentType" :value="item.graph_id"/>
                  </div>
                  <div class="card-content">
                    <div class="coll_name" v-if="item.config.configurable">数据KEY：{{ item.config.configurable.collection_name }}</div>
                    <!-- <div class="user">归属用户：{{ item.config.configurable.user_id }}</div> -->
                    <div class="id">{{ item.assistant_id }}</div>
                  </div>
                  <div class="card-bottom">
                    <div class="v">v{{ item.version }}</div>
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-folder-opened"
                      @click="handleAddData(item)"
                    >设置数据</el-button>
                    
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDeleteAdd(item)"
                    >删除</el-button>
                  </div>
                </div>
            </el-card>
          </el-col>
        </el-checkbox-group>

      </el-row>

      <div class="bg-grey page-posi-div" v-show="total>0">
        <div class="bg-fff bor-r-10 p10 pb20">
          <pagination
          :total="total"
          :pageSizes="[8,12,16,24]"
          :page.sync="queryP.pageNum"
          :limit.sync="queryP.limit"
          @pagination="getList"
          />
        </div>
      </div>

  </div>
</template>

<script>
import langC from "@/api/wenda/langChain";
import XiangLiang from './XiangLiang.vue'
import AddDocs from './AddDocs.vue'
import AgentForm from './AgentForm.vue'

export default {
  name: "Post",
  components: { XiangLiang, AddDocs, AgentForm},
  dicts: ['sys_normal_disable'],
  data() {
    return {
      agentType:[{value:'indexer',label:"向量数据库",raw:{listClass:'warning'}}],

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      names:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      agentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryP: {
        pageNum:1,
        offset: 0,
        limit: 12,
        name: "",
        graphId: "indexer",
        metadata: {},
      },
      // 表单参数
      form: {},
      isDis :false,
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        graph_id: [
          { required: true, message: "助手类型不能为空", trigger: "blur" }
        ],
      },
      rulesAdd: {
        assistantId: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        input: [
          { required: true, message: "数据不能为空", trigger: "blur" }
        ],
        streamMode: [
          { required: true, message: "类型不能为空", trigger: "blur" }
        ]
      },

      openAdd:false,
      formAdd:{assistantId:'',docsStr:"[]",streamMode: ["debug","messages"]},
      titleAdd:'',
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 通过点击 div 切换复选框状态
    toggleCheckbox(item) {

      item.checked = !item.checked;
      console.log(item)
      this.updateIdsArray(item);
    },
    updateIdsArray(item) {
      const index = this.ids.indexOf(item.assistant_id);
      if (item.checked) {
        if (index === -1) this.ids.push(item.assistant_id);
      } else {
        if (index !== -1) this.ids.splice(index, 1);
      }
      this.handleSelectionChange()
      console.log(this.ids)
    },

    upConfig(e){
      if(e=='retrieval_graph'){
        this.agentC = this.graphC
      }else if(e=="indexer"){
        this.agentC = this.indexerC
      }
    },
    /** 查询岗位列表 */
    getList() {
      this.cancel()
      this.loading = true;
      let q = {...this.queryP}
      this.queryP.offset = (this.queryP.pageNum-1)*this.queryP.limit
      // console.log(this.queryP)
      langC.agentList(this.queryP).then(res => {
        // console.log("agentList:",res)
        this.agentList = res
        this.loading = false;
      });
      q.limit = 999
      q.offset = 0
      langC.agentList(q).then(res => {
        this.total = res.length
      });
    },
    // 取消按钮
    cancel() {
      this.ids = [];
      this.handleSelectionChange()

      this.openAdd = false;
      this.open = false;
      this.isDis =!1
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
      };
      this.formAdd = {}
      this.agentC = {}
      this.isDis =!1
      this.resetForm("form");
      this.resetForm("formAdd");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      //   this.queryP.offset = 10;
      console.log(this.queryP)
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange() {
      if(this.ids.length==1){
        this.assistant_id = this.ids[0]
      }else{
        this.assistant_id = ""
      }
      this.single = this.ids.length!=1
      this.multiple = !this.ids.length
    },
    /** 新增按钮操作 */
    handleAddData(row) {
      this.reset();
      this.formAdd = {assistantId:row.assistant_id,docsStr:'["321321321321","4544645646544646","7879879798797987987"]',streamMode: ["debug","messages"]}
      this.openAdd = true;
      this.titleAdd = "添加文档";
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.isDis =!1
      this.title = "添加助手";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.assistant_id || this.assistant_id
      langC.agentGet(id).then(res => {
        console.log(res)
        this.agentC = res.config
        res.configStr = JSON.stringify(res.config)
        this.isDis = true
        this.form = res;
        this.open = true;
        this.title = "修改助手";
      });
    },
    async submitAddData() {

      const valid = await this.$refs.addDataForm.validate()
      if (!valid) return

      const formData = this.$refs.addDataForm.getFormData()
      let thread = await langC.threadCreate({
        "thread_id": "",
        "metadata": { graph_id: "indexer", assistantId: formData.assistantId, },
        "if_exists": "raise",
      })
      if (!thread) {
        this.$modal.msgError("创建会话失败")
        return false
      }
      try {
        const docsArr = JSON.parse(formData.docsStr)
        formData.assistant_id = formData.assistantId
        formData.stream_mode = formData.streamMode
        formData.input = { docs: docsArr }
        const res = await fetch("/langC/threads/" + thread.thread_id + "/runs/stream", {
          method: 'post',
          body:JSON.stringify(formData),
          responseType: 'srteam',
          headers: {
            'Content-Type': 'application/json',
          }
        })
        setTimeout(() => {
          console.log("submitAddData-res:",res);
        }, 3000);

        this.$modal.msgSuccess("新增成功");
        this.openAdd = false;
        // this.reset()
        // this.cancel()
      } catch (error) {
        console.error("请求失败:", error);
        this.$modal.msgError("操作失败，请重试");
      }
    },
    /** 提交按钮 */
    async submitForm() {
      const valid = await this.$refs.agentForm.validateForm()
      if (!valid) return

      let res;
      try {
        let formData = this.$refs.agentForm.getFormData()
        formData.assistantId = formData.assistant_id
        formData.graphId = formData.graph_id
        if (formData.graph_id != 'agent') {
          formData.config = { configurable: formData.config.configurable }
        } else {
          formData.config = JSON.parse(this.form.config) // 只有agent才需要转换，其余都有对应的默认配置
        }

        console.log("submitForm-formData:", formData);
        if (formData.assistant_id != undefined) {
          res = await langC.agentUpdate(formData.assistant_id, formData);
          this.$modal.msgSuccess("修改成功");
        } else {
          formData.ifExists = "raise"
          console.log("submitForm-form:", formData);
          res = await langC.agentCreate(formData); // 添加 await
          this.$modal.msgSuccess("新增成功");
        }
        console.log("submitForm-res:", res);
        this.cancel()
        this.getList();
      } catch (error) {
        console.error("请求失败:", error);
        this.$modal.msgError("操作失败，请重试");
      }
    },
    /** 删除按钮操作 */
    async handleDeleteAdd(row) {
      // console.log(row.config.configurable.collection_name)
      console.log(row)
      let collname = row.config.configurable.collection_name
      let aa
      this.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项？').then(() => {
        aa = langC.delLangC(collname);
      }).then(() => {
          console.log("AAAAA:::::",aa)
          this.handleDelete(row);
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    async handleDelete(row) {
     
     console.log(row)
     const names = this.ids.length?'是否确认删除'+this.ids.length+'个数据项？':'是否确认删除名称为"' + row.name + '"的数据项？'
     const id = row.assistant_id
     console.log(row)
     console.log(names)
     console.log(this.ids)

     this.$modal.confirm(names).then(() => {
       if(this.ids.length){
             for (let i = 0; i < this.ids.length; i++) {
                 console.log(this.ids[i])
                 langC.agentDelete(this.ids[i]);
             }
             return true
         }else{
             
             langC.agentDelete(id);
         }
     }).then(() => {
         this.$modal.msgSuccess("删除成功");
         setTimeout(() => {
             this.getList();
         }, 1000);
     }).catch(() => {
       this.getList()
     });
   },
 }
};
</script>
